package com.xianshijian.oauth.server.steps;

import java.net.URI;

import javax.servlet.http.Cookie;

import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.xianshijian.oauth.server.AbstractSpringCucumber;

import cucumber.api.java.zh_cn.假设;
import cucumber.api.java.zh_cn.当;
import cucumber.api.java.zh_cn.那么;

public class AuthStepdef extends AbstractSpringCucumber {
	ResultActions ra;
	private String password = "admin";
	private String username = "admin";
	private String redirectUrl = "http://www.baidu.com";

	@假设("^我在授权页$")
	public void 我在授权页() throws Throwable {
		// TODO 清理表创建初始数据

		mvc = MockMvcBuilders.webAppContextSetup(wac).build();
		// 用户登录.
		// 请求到登录页面.
		URI loginUrl = URI.create("/api/login");
		ra = mvc.perform(MockMvcRequestBuilders.post(loginUrl).param("username", username).param("password", password));
		// 保存cookies
		ra.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
	}

	@当("^我点击了允许授权按钮$")
	public void 我点击了允许授权按钮() throws Throwable {
		URI authUrl = URI.create("/api/auth");
		ra = mvc.perform(MockMvcRequestBuilders.post(authUrl).cookie(new Cookie("sesssionId", "11111")));
	}

	@那么("^我应该回到第三方页面$")
	public void 我应该回到第三方页面() throws Throwable {
		String expectedUrl = redirectUrl;
		ra.andExpect(MockMvcResultMatchers.redirectedUrl(expectedUrl));
	}

	@那么("^第三方能够访问我的资源$")
	public void 第三方能够访问我的资源() throws Throwable {
		URI userinfoUri = URI.create("http://localhost:8080/users/1");
		ra = mvc.perform(MockMvcRequestBuilders.get(userinfoUri));
		ra.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
	}

}
